﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using RecipeBookBusiness;

namespace RecipeBookWeb
{
    public partial class Search : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //Populate SearchTypeDropDownList
                SearchTypeDropDownList.Items.Clear();
                SearchTypeDropDownList.Items.Add(new ListItem("Recipe Name", "1"));
                SearchTypeDropDownList.Items.Add(new ListItem("Category", "2"));
                SearchTypeDropDownList.Items.Add(new ListItem("Ingredients", "3"));
                SearchTypeDropDownList.Items.Add(new ListItem("User", "4"));
            } 
            
            //If the search is coming from another page
            if (Session["PageRedirect"] != null)
            {
                if (Session["SearchType"] != null)
                {
                    SearchTypeDropDownList.SelectedValue = Session["SearchType"].ToString();
                    SearchTypeDropDownList.DataBind();
                }
                if (Session["SearchValue"] != null)
                {
                    SearchTextBox.Text = Session["SearchValue"].ToString();
                    SearchTextBox.DataBind();
                }
                if (Session["SearchValue"] != null && Session["SearchType"] != null)
                {
                    search();
                }
                //Reset it so that we're searching on our main page now
                Session["PageRedirect"] = null;
            }
        }

        protected void SearchButton_Click(object sender, EventArgs e)
        {
            Session["SearchType"] = Convert.ToInt32(SearchTypeDropDownList.SelectedValue);
            Session["SearchValue"] = SearchTextBox.Text.Trim();
            search();
        }

        private void search()
        {
            DataSet searchResults = ModelFacade.SearchRecipes((int)Session["SearchType"], Session["SearchValue"].ToString());
            if (searchResults.Tables.IndexOf("Recipes") >= 0 && searchResults.Tables["Recipes"].Rows.Count > 0)
            {
                NoResultsLabel.Visible = false;
                SearchResultsGridView.Visible = true;
                DataTable recipeTable = searchResults.Tables["Recipes"];
                SearchResultsGridView.DataSource = recipeTable;
                SearchResultsGridView.DataBind();
            }
            else
            {
                NoResultsLabel.Visible = true;
                SearchResultsGridView.Visible = false;
            }
            NoResultsLabel.DataBind();
        }
    }
}
